package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 陈辉
 * @data 2024 14:48
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //全局登录验证
        //1. 判断当前请求是否需要验证：登陆相关资源不需要验证，直接放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();
        log.info("拦截到本次请求路径：{}",path);

        if (path.contains("login")){
           return chain.filter(exchange);
        }

        //2. 解析请求头，获取token
        String token = request.getHeaders().getFirst("token");

        //3. 验证token
        //3.1 验证不通过：返回401
        //情况1： 压根没给token
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //情况2： 伪造token
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //-1：有效，0：有效，1：过期，2：过期
            int res = AppJwtUtil.verifyToken(claimsBody);
            if (res != -1 && res != 0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //解析出token中的原始数据：当前登录用户id
            Object userId = claimsBody.get("id");

            // 往下游微服务路由时追加请求头：userId = 当前登录用户id
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();

            //重置header
            exchange.mutate().request(serverHttpRequest).build();


        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3.2 验证通过：放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
